package com.spic.business.train.year.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.enums.CellExtraTypeEnum;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.spic.business.train.plan.domain.TrainPlan;
import com.spic.business.train.plan.domain.YearPlanExcel;
import com.spic.business.train.plan.domain.YearPlanReadListener;
import com.spic.business.train.plan.service.YearPlanService;
import com.spic.business.train.year.domain.TrainPlanYear;
import com.spic.business.train.year.service.ITrainPlanYearService;
import com.spic.common.core.domain.R;
import com.spic.common.core.utils.SecurityUtils;
import com.spic.common.core.utils.StringUtils;
import com.spic.common.core.utils.poi.ExcelUtil;
import com.spic.common.core.web.controller.BaseController;
import com.spic.common.core.web.domain.AjaxResult;
import com.spic.common.core.web.page.TableDataInfo;
import com.spic.common.log.annotation.Log;
import com.spic.common.log.enums.BusinessType;
import com.spic.common.security.utils.DictUtils;
import com.spic.common.security.utils.cache.DeptCacheUtils;
import com.spic.system.api.RemoteDeptService;
import com.spic.system.api.domain.SysDictData;
import com.spic.system.api.dto.DeptDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 年度培训计划Controller
 *
 * @author yangjie
 * @date 2021-11-24
 */
@RestController
@RequestMapping("/train/year")
public class TrainPlanYearController extends BaseController
{
    @Autowired
    private ITrainPlanYearService trainPlanYearService;

    @Autowired
    private YearPlanService yearPlanService;

    @Autowired
    private RemoteDeptService remoteDeptService;
    /**
     * 查询年度培训计划列表
     */
//    @PreAuthorize(hasPermi = "business/train:year:list")
    @GetMapping("/list")
    public TableDataInfo list(TrainPlanYear trainPlanYear)
    {
        startPage();
        List<TrainPlanYear> list = trainPlanYearService.selectTrainPlanYearList(trainPlanYear);
        return getDataTable(list);
    }

    /**
     * 导出年度培训计划列表
     */
//    @PreAuthorize(hasPermi = "business/train:year:export")
    @Log(title = "年度培训计划", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TrainPlanYear trainPlanYear) throws IOException
    {
        List<TrainPlanYear> list = trainPlanYearService.selectTrainPlanYearList(trainPlanYear);
        ExcelUtil<TrainPlanYear> util = new ExcelUtil<TrainPlanYear>(TrainPlanYear.class);
        util.exportExcel(response, list, "年度培训计划数据");
    }

    /**
     * 获取年度培训计划详细信息
     */
//    @PreAuthorize(hasPermi = "business/train:year:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(trainPlanYearService.selectTrainPlanYearById(id));
    }

    /**
     * 新增年度培训计划
     */
//    @PreAuthorize(hasPermi = "business/train:year:add")
//    @Log(title = "年度培训计划", businessType = BusinessType.INSERT)
//    @PostMapping
//    public AjaxResult add(@RequestBody TrainPlanYear trainPlanYear)
//    {
//        return toAjax(trainPlanYearService.insertTrainPlanYear(trainPlanYear));
//    }

    /**
     * 修改年度培训计划
     */
//    @PreAuthorize(hasPermi = "business/train:year:edit")
    @Log(title = "年度培训计划", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TrainPlanYear trainPlanYear)
    {
        return toAjax(trainPlanYearService.updateTrainPlanYear(trainPlanYear));
    }

    /**
     * 删除年度培训计划
     */
//    @PreAuthorize(hasPermi = "business/train:year:remove")
    @Log(title = "年度培训计划", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(trainPlanYearService.deleteTrainPlanYearByIds(ids));
    }


    @GetMapping("template")
    public void  downloadTemplate()
    {
        EasyExcel.write("template-year-plan.xlsx", TrainPlan.class).sheet().doWrite(new ArrayList<TrainPlan>());

    }

    @PostMapping("exportPlan")
    public void  exportPlan(HttpServletResponse response, YearPlanExcel trainPlanYear)
    {
        try
        {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            List<YearPlanExcel> list = yearPlanService.list(new QueryWrapper<YearPlanExcel>(trainPlanYear));
            String year = (list == null || list.size() < 1) ? "" : list.get(0).getYear();
            String bigHeader = "南露天煤矿" + year +"年安全培训计划";
            String fileName = URLEncoder.encode(bigHeader, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            List<List<String>> header = Lists.newArrayList(
                    Lists.newArrayList(bigHeader, "培训类别"),
                    Lists.newArrayList(bigHeader, "序号"),
                    Lists.newArrayList(bigHeader, "申报部门"),
                    Lists.newArrayList(bigHeader, "培训项目名称"),
                    Lists.newArrayList(bigHeader, "培训方式"),
                    Lists.newArrayList(bigHeader, "培训师选用方式"),
                    Lists.newArrayList(bigHeader, "培训师"),
                    Lists.newArrayList(bigHeader, "培训机构\n" + "与地点"),
                    Lists.newArrayList(bigHeader, "参培人员"),
                    Lists.newArrayList(bigHeader, "人员类别及参培人数", "领导班子"),
                    Lists.newArrayList(bigHeader, "人员类别及参培人数", "中层管理人员"),
                    Lists.newArrayList(bigHeader, "人员类别及参培人数", "一般管理人员"),
                    Lists.newArrayList(bigHeader, "人员类别及参培人数", "员工", "工队长"),
                    Lists.newArrayList(bigHeader, "人员类别及参培人数", "员工","安全员"),
                    Lists.newArrayList(bigHeader, "人员类别及参培人数", "员工", "岗位员工"),
                    Lists.newArrayList(bigHeader, "人员类别及参培人数", "员工", "外委人员"),
                    Lists.newArrayList(bigHeader, "人员类别及参培人数", "合计"),
                    Lists.newArrayList(bigHeader, "培训起止时间"),
                    Lists.newArrayList(bigHeader, "办班数"),
                    Lists.newArrayList(bigHeader, "天数"),
                    Lists.newArrayList(bigHeader, "课时/班"),
                    Lists.newArrayList(bigHeader, "总课时"),
                    Lists.newArrayList(bigHeader, "费用预测（元）", "讲课酬金"),
                    Lists.newArrayList(bigHeader, "费用预测（元）", "培训费"),
                    Lists.newArrayList(bigHeader, "费用预测（元）", "差旅费"),
                    Lists.newArrayList(bigHeader, "费用预测（元）", "资料费"),
                    Lists.newArrayList(bigHeader, "费用预测（元）", "其他"),
                    Lists.newArrayList(bigHeader, "费用预测（元）", "合计"),
                    Lists.newArrayList(bigHeader, "考核方式")
            );

            //转换字典数据
            List<DeptDTO> deptDTOList = DeptCacheUtils.getCache();
            Map<Long, String> data = deptDTOList.stream().filter(item ->
                    {
                        String ancestors = item.getAncestors();
                        if (org.apache.commons.lang3.StringUtils.isNotBlank(ancestors))
                        {
                            return ancestors.split(",").length == 2;
                        }
                        else
                        {
                            return true;
                        }
                    }
            ).collect(Collectors.toMap(DeptDTO::getDeptId, DeptDTO::getDeptName, (k1, k2) -> k2));

            List<SysDictData> methods = DictUtils.getDictCache("train_method");
            Map<String, String> methodMap = methods.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            List<SysDictData> ways = DictUtils.getDictCache("choose_way");
            Map<String, String> waysMap = ways.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            List<SysDictData> asses = DictUtils.getDictCache("assessment_method");
            Map<String, String> assesMap = asses.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            for (int i = 0; i < list.size(); i++)
            {
                YearPlanExcel yearPlanExcel = list.get(i);
                yearPlanExcel.setNum(String.valueOf(i + 1));
                yearPlanExcel.setDeptName(data.get(yearPlanExcel.getTrainDept()));
                yearPlanExcel.setChooseWay(waysMap.get(yearPlanExcel.getChooseWay()));
                yearPlanExcel.setTrainMethod(methodMap.get(yearPlanExcel.getTrainMethod()));
                yearPlanExcel.setAssessmentMethod(assesMap.get(yearPlanExcel.getAssessmentMethod()));
            }
            EasyExcel.write(response.getOutputStream(), YearPlanExcel.class).autoCloseStream(Boolean.FALSE).head(header).sheet().doWrite(list);
        }
        catch (IOException e)
        {
//            e.printStackTrace();
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            AjaxResult result = AjaxResult.error(e.getMessage());
            try
            {
                response.getWriter().println(JSON.toJSONString(result));
            }
            catch (IOException ioException)
            {
                ioException.printStackTrace();
            }
        }

    }

    @PostMapping("add")
    public AjaxResult add(@RequestBody YearPlanExcel yearPlanExcel)
    {
        yearPlanExcel.setDeptId(Long.valueOf(SecurityUtils.getDeptId()));
        yearPlanExcel.setCreateBy(SecurityUtils.getUserId().toString());
        return AjaxResult.success(yearPlanService.save(yearPlanExcel));
    }

    @PostMapping("update")
    public AjaxResult update(@RequestBody YearPlanExcel yearPlanExcel)
    {
        return AjaxResult.success(yearPlanService.updateById(yearPlanExcel));
    }

    @PostMapping("delete/{ids}")
    public AjaxResult deleteByIds(@PathVariable String[] ids)
    {
        return toAjax(yearPlanService.removeByIds(Arrays.asList(ids)));
    }

    @GetMapping("item/{id}")
    public AjaxResult getItemById(@PathVariable("id") String id)
    {
        return AjaxResult.success(yearPlanService.getById(id));
    }


    @PostMapping("importPlan")
    public AjaxResult importData(MultipartFile file, boolean updateSupport)
    {

        AjaxResult ajaxResult = AjaxResult.success();

        R<Map<String,Long>> r = remoteDeptService.cache2();

        InputStream inputStream = null;
        try
        {
            inputStream = file.getInputStream();
        }
        catch (IOException e)
        {
            logger.error("import file,read stream error.");
        }
        EasyExcel.read(inputStream, YearPlanExcel.class, new YearPlanReadListener(ajaxResult, yearPlanService)).autoTrim(true).extraRead(CellExtraTypeEnum.MERGE).headRowNumber(4).sheet().doRead();
        return ajaxResult;
    }

    @GetMapping("page")
    public TableDataInfo page(YearPlanExcel yearPlanExcel)
    {
        List<Long> trainTypes = null;
        //获取部门及子部门
        if (StringUtils.isNotEmpty(yearPlanExcel.getTrainType())){
            trainTypes = remoteDeptService.getDeptAndChildren(Long.parseLong(yearPlanExcel.getTrainType())).getData();
            yearPlanExcel.setTrainType(null);
        }
        QueryWrapper<YearPlanExcel> yearPlanExcelQueryWrapper = new QueryWrapper<>(yearPlanExcel);
        yearPlanExcelQueryWrapper.in(!CollectionUtils.isEmpty(trainTypes),"train_type",trainTypes);
        startPage();
        List<YearPlanExcel> list = yearPlanService.list(yearPlanExcelQueryWrapper);
        return getDataTable(list);
    }
}
